#!/bin/sh

## usage: play [-a] [selector_name [selector_args...]]
# -a -> play -a; no -a -> play
# selector == local must not take selector_args

abspath() {
	echo "$(cd "$(dirname "$1")" >/dev/null||exit; pwd)/"
}

DATA_HOME=${XDG_DATA_HOME:-"$HOME/.local/share"}
XDG_DATA_DIRS=${XDG_DATA_DIRS:-/usr/local/share/:/usr/share/}

XDG_DIRS="$DATA_HOME:$XDG_DATA_DIRS"
SELECTOR_DIRS=''
IFS=':'; for dir in $XDG_DIRS
do
	SELECTOR_DIRS="$SELECTOR_DIRS:$dir/music/selectors"
done
SELECTOR_DIRS="$(abspath "$0")${SELECTOR_DIRS}"

mkdir -p "$DATA_HOME/music/selectors"

name="$(basename "$0")"

if [ "$1" = '-h' ]
then
	if [ "$name" = 'play' ]
	then
		append_arg='[-a] '
		action="Play"
		options="
Options:
 -a\t\tappend to queue\n"
	else
		action="Enqueue"
	fi
	printf "
Usage:
\t%s %s[selector_name [selector_args]]

%s music
%b
For more details see %s(1)\n" "$0" "$append_arg" "$action" "$options" "$name"
	exit
fi

if [ "$1" = '-a' ] || [ "$name" = 'queue' ]
then
	append="-a"
	if [ "$1" = '-a' ]
	then
		shift
	fi
fi

if [ "$1" = "" ]
then
	selector_name='local'
else
	selector_name="$1"
	shift
fi

IFS=':'; for dir in $SELECTOR_DIRS
do
	if [ -d "$dir" ] && ls "$dir" | grep "$selector_name" >/dev/null
	then
		selector="$dir/$selector_name/select"
		break
	fi
done

if [ "$selector" ]
then
	PATH="$(abspath "$0"):$PATH"
	$selector "$@" | music $append
else
	echo "selector ‘$selector_name’ not found"
fi

